package com.xinpu.controller;


import com.xinpu.util.UploadFileUtil;
import com.xinpu.vo.ResponseMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * UploadController
 *
 * @author ayuan
 * @date 2020/10/16
 */
@RestController
@RequestMapping("/upload")
@Api(tags = "图片上传有关接口")
public class UploadController {


    @Value("${mapUrl.path}")
    private String path;

    @Value("${mapUrl.mapPath}")
    private String mapPath;

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadImages")
    @ApiOperation("图片上传")
    public ResponseMessage uploadImages(MultipartFile file) {
        try {
            byte[] bytes = file.getBytes();
            // 后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 得到新的图片名
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            UploadFileUtil.uploadFile(bytes, path, newFileName);
            return ResponseMessage.ok(mapPath + newFileName);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return ResponseMessage.error("上传失败");
        }
    }

}
